<?php

/**
 * This is the model class for table "employees".
 *
 * The followings are the available columns in table 'employees':
 * @property integer $id
 * @property string $name
 * @property string $code
 * @property string $gender
 * @property string $matrimony
 * @property string $birthDate
 * @property string $employmentStatus
 * @property string $employmentDate
 * @property string $expiredDate
 * @property string $unemploymentDate
 * @property string $position
 * @property string $division
 * @property string $group
 * @property integer $supervisorId
 * @property string $address
 * @property string $email
 * @property string $workAt
 * @property string $workLocation
 * @property string $leaveBalanceDefault
 * @property string $leaveBalance
 * @property string $createdAt
 * @property string $updatedAt
 * @property integer $createdBy
 * @property integer $updatedBy
 * @property integer $isSupervisor
 * @property string $workAt
 * @property string $workLocation
 * @property integer $userId
 */
class Employee extends ActiveRecordUser {

	const EMPLOYMENT_STATUS_CONTRACT = 'Contract';
	const EMPLOYMENT_STATUS_PERMANENT = 'Permanent';
	const WORK_AT_HO = 'HO';
	const WORK_AT_NON_HO = 'Non HO';

	public $photo;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Employee the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'employees';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name', 'required'),
			array(
				'supervisorId, isSupervisor, isManagement',
				'numerical',
				'integerOnly'=>true,
			),
			array(
				'leaveBalanceDefault, leaveBalance',
				'numerical',
				'integerOnly'=>true,
				'min'=>0,
			),
			array('name, email', 'length', 'max'=>128),
			array('email', 'email'),
			array('code, gender, workAt', 'length', 'max'=>8),
			array(
				'position, division, group, workLocation',
				'length',
				'max'=>32
			),
			array('code', 'unique'),
			array('matrimony, employmentStatus', 'length', 'max'=>16),
			array(
				'birthDate, employmentDate, expiredDate, unemploymentDate',
				'date',
				'format'=>'yyyy-MM-dd',
			),
			array(
				'userId',
				'unique',
			),
			array(
				'employmentStatus',
				'YiiConditionalValidator',
				'validation'=>array(
					'compare',
					'compareValue'=>self::EMPLOYMENT_STATUS_CONTRACT
				),
				'dependentValidations'=>array(
					'expiredDate'=>array(
						array(
							'required',
							'message'=>'{dependentAttribute} is required if ' .
							'the {attribute} specified is {value}.'
						),
					),
				),
			),
			array(
				'workAt',
				'YiiConditionalValidator',
				'validation'=>array(
					'compare',
					'compareValue'=>self::WORK_AT_NON_HO
				),
				'dependentValidations'=>array(
					'workLocation'=>array(
						array(
							'required',
							'message'=>'{dependentAttribute} is required if ' .
							'the {attribute} specified is {value}.'
						),
					),
				),
			),
			array(
				'photo',
				'file',
				'types'=>'png, gif, jpg',
				'allowEmpty'=>true
			),
			array('address, createdAt, updatedAt', 'safe'),
			array(
				'id, name, code, gender, matrimony, birthDate, ' .
				'employmentStatus, employmentDate, expiredDate, ' .
				'unemploymentDate, position, division, group, supervisorId, ' .
				'address, email, isSupervisor, workAt, workLocation',
				'safe',
				'on'=>'search'
			),
		);
	}

	protected function beforeValidate() {
		if ($this->employmentStatus == self::EMPLOYMENT_STATUS_PERMANENT) {
			$this->expiredDate = null;
		}
		if ($this->workAt == self::WORK_AT_HO) {
			$this->workLocation = null;
		}
		return parent::beforeValidate();
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'supervisor'=>array(self::BELONGS_TO, 'Employee', 'supervisorId'),
			'insurances'=>array(
				self::HAS_MANY,
				'Insurance',
				'ownerId',
				'condition'=>'ownerClass = :ownerClass',
				'params'=>array(':ownerClass'=>'Employee'),
			),
			'families'=>array(self::HAS_MANY, 'Family', 'employeeId'),
			'banks'=>array(self::HAS_MANY, 'Bank', 'employeeId'),
			'leaves'=>array(self::HAS_MANY, 'Leave', 'employeeId'),
			'identities'=>array(self::HAS_MANY, 'Identity', 'employeeId'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'id'=>'ID',
			'name'=>'Name',
			'code'=>'NIK',
			'gender'=>'Gender',
			'matrimony'=>'Matrimony',
			'birthDate'=>'Birth Date',
			'unixBirthDate'=>'Birth Date',
			'employmentStatus'=>'Employment Status',
			'employmentDate'=>'Employment Date',
			'unixEmploymentDate'=>'Employment Date',
			'expiredDate'=>'Contract Expired Date',
			'unixExpiredDate'=>'Contract Expired Date',
			'unemploymentDate'=>'Unemployment Date',
			'unixUnemploymentDate'=>'Unemployment Date',
			'position'=>'Position',
			'division'=>'Division',
			'group'=>'Group',
			'supervisorId'=>'Supervisor',
			'supervisor.name'=>'Supervisor',
			'address'=>'Address',
			'email'=>'Email',
			'isSupervisor'=>"I'm Supervisor",
			'workAt'=>'Work Location',
			'workLocation'=>'Location',
			'leaveBalanceDefault'=>'Default Leave Balance',
			'leaveBalance'=>'Leave Balance',
			'createdAt'=>'Created At',
			'updatedAt'=>'Updated At',
			'createdBy'=>'Created By',
			'updatedBy'=>'Updated By',
			'userId'=>'User Account',
			'isManagement'=>"I'm Management",
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search() {
		$criteria = new CDbCriteria;

		$criteria->order = 'name';
		$criteria->compare('id', $this->id);
		$criteria->compare('name', $this->name, true);
		$criteria->compare('code', $this->code, true);
		$criteria->compare('gender', $this->gender, true);
		$criteria->compare('matrimony', $this->matrimony, true);
		$criteria->compare('birthDate', $this->birthDate, true);
		$criteria->compare('employmentStatus', $this->employmentStatus, true);
		$criteria->compare('employmentDate', $this->employmentDate, true);
		$criteria->compare('expiredDate', $this->expiredDate, true);
		$criteria->compare('unemploymentDate', $this->unemploymentDate, true);
		$criteria->compare('position', $this->position, true);
		$criteria->compare('division', $this->division, true);
		$criteria->compare('group', $this->group, true);
		$criteria->compare('supervisorId', $this->supervisorId);
		$criteria->compare('address', $this->address, true);
		$criteria->compare('email', $this->email, true);
		$criteria->compare('isSupervisor', $this->id);
		$criteria->compare('workAt', $this->address, true);
		$criteria->compare('workLocation', $this->address, true);

		return new CActiveDataProvider($this, array('criteria'=>$criteria));
	}

	public function getMenu($action, $toolbar = false) {
		$name = 'Employee';
		$user = Yii::app()->user;
		$tool = Yii::app()->request->baseUrl . '/images/toolbars';
		$menu = array();

		$label = "View $name";
		if ($toolbar) $label = "<img src=\"$tool/magnifier-left.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array('view', 'id'=>$this->id),
			'visible'=>$action != 'view' && $user->checkAccess("$name.View"),
			'linkOptions'=>array('title'=>'View'),
		);

		$label = "Update $name";
		if ($toolbar) $label = "<img src=\"$tool/pencil.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array('update', 'id'=>$this->id),
			'visible'=>$action != 'update' &&
			$user->checkAccess("$name.Update"),
			'linkOptions'=>array('title'=>'Update'),
		);

		$label = "List Leave";
		if ($toolbar) $label = "<img src=\"$tool/luggage.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array(
				'leave/index',
				CHtml::activeName(Leave::model(), 'employeeId')=>$this->id
			),
			$user->checkAccess('Leave.Index'),
			'linkOptions'=>array('title'=>'List Leave'),
		);

		$family = Family::model();
		$label = "Add Family";
		if ($toolbar) $label = "<img src=\"$tool/user--plus.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array(
				'family/create',
				CHtml::activeName($family, 'employeeId')=>$this->id
			),
			$user->checkAccess('Family.Create'),
			'linkOptions'=>array('title'=>'Add Family'),
		);

		$label = "List Family";
		if ($toolbar) $label = "<img src=\"$tool/users.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array(
				'family/index',
				CHtml::activeName($family, 'employeeId')=>$this->id
			),
			$user->checkAccess('Family.Index'),
			'linkOptions'=>array('title'=>'List Family'),
		);

		$insurance = Insurance::model();
		$label = "Add Insurance";
		if ($toolbar) $label = "<img src=\"$tool/wall--plus.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array(
				'insurance/create',
				'ownerClass'=>__CLASS__,
				'ownerId'=>$this->id,
			),
			$user->checkAccess('Insurance.Create'),
			'linkOptions'=>array('title'=>'Add Insurance'),
		);

		$label = "List Insurance";
		if ($toolbar) $label = "<img src=\"$tool/wall.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array(
				'insurance/index',
				CHtml::activeName($insurance, 'ownerClass')=>__CLASS__,
				CHtml::activeName($insurance, 'ownerId')=>$this->id,
			),
			$user->checkAccess('Insurance.Index'),
			'linkOptions'=>array('title'=>'List Insurance'),
		);

		$bank = Bank::model();
		$label = "Add Bank";
		if ($toolbar) $label = "<img src=\"$tool/bank--plus.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array(
				'bank/create',
				CHtml::activeName($bank, 'employeeId')=>$this->id
			),
			$user->checkAccess('Bank.Create'),
			'linkOptions'=>array('title'=>'Add Bank'),
		);

		$label = "List Bank";
		if ($toolbar) $label = "<img src=\"$tool/bank.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array(
				'bank/index',
				CHtml::activeName($bank, 'employeeId')=>$this->id
			),
			$user->checkAccess('Bank.Index'),
			'linkOptions'=>array('title'=>'List Bank'),
		);

		$identity = Identity::model();
		$label = "Add Identity";
		if ($toolbar) $label = "<img src=\"$tool/credit-card--plus.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array(
				'identity/create',
				CHtml::activeName($identity, 'employeeId')=>$this->id
			),
			$user->checkAccess('Identity.Create'),
			'linkOptions'=>array('title'=>'Add Identity'),
		);

		$label = "List Identity";
		if ($toolbar) $label = "<img src=\"$tool/credit-card.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array(
				'identity/index',
				CHtml::activeName($identity, 'employeeId')=>$this->id
			),
			$user->checkAccess('Identity.Index'),
			'linkOptions'=>array('title'=>'List Identity'),
		);

		$label = "Generate Card";
		if ($toolbar) $label = "<img src=\"$tool/card-address.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>array('card', 'id'=>$this->id),
			'visible'=>$action != 'view' && $user->checkAccess("$name.Card"),
			'linkOptions'=>array('title'=>'Generate Card'),
		);

		$label = "Delete $name";
		if ($toolbar) $label = "<img src=\"$tool/cross-script.png\" />";
		$menu[] = array(
			'label'=>$label,
			'url'=>'#',
			'visible'=>$user->checkAccess("$name.Delete"),
			'linkOptions'=>array(
				'submit'=>array('delete', 'id'=>$this->id),
				'confirm'=>'Are you sure you want to delete this item?',
				'title'=>'Delete',
			)
		);
		return $menu;
	}

	public function behaviors() {
		return array(
			'photoBehavior'=>array(
				'class'=>'application.behaviors.ImageARBehavior',
				'attribute'=>'photo',
				'extension'=>'png, gif, jpg',
				'prefix'=>'',
				'relativeWebRootFolder'=>'files/employees/photos',
				'forceExt'=>'png',
				'useImageMagick'=>null,
				'formats'=>array(
					'thumb'=>array(
						'suffix'=>'.thumb',
						'process'=>array('resize'=>array(150, 1000, 4)),
					),
					'normal'=>array(
					),
				),
				'defaultName'=>'default',
			),
			'dataProvider'=>array(
				'class'=>'application.behaviors.DynamicDataProviderBehavior',
			),
			'genderBehavior'=>array(
				'class'=>'application.behaviors.GenderListBehavior',
				'attribute'=>'gender',
			),
			'matrimonyBehavior'=>array(
				'class'=>'application.behaviors.MatrimonyListBehavior',
				'attribute'=>'matrimony',
			),
			'autoComplete'=>array(
				'class'=>'application.behaviors.AutoCompleteBehavior',
			),
		);
	}

	public function getCardFront() {
		$webroot = Yii::getPathOfAlias('webroot');
		$path = "$webroot/files/employees/ids/front.jpg";
		$background = ImageCreateFromJpeg($path);
		$x = 86;
		$y = 160;
		$width = 105;
		$height = 154;
		$photo = $this->_cropPhoto($width, $height);
		ImageCopyMerge(
			$background, $photo, $x, $y, 0, 0, $width, $height, 100
		);
		$color = imagecolorallocate($background, 0, 0, 0);
		$text = $this->name;
		$this->_imageStringCutted($background, 5, 325, 0, 280, $text, $color);
		$text = $this->code;
		$this->_imageStringCutted($background, 5, 345, 0, 280, $text, $color);
		$path = "$webroot/files/employees/ids/{$this->id}.png";
		imagepng($background, $path);
		$baseUrl = Yii::app()->request->baseUrl;
		return "$baseUrl/files/employees/ids/{$this->id}.png";
	}

	public function getCardRear() {
		$baseUrl = Yii::app()->request->baseUrl;
		return "$baseUrl/files/employees/ids/rear.jpg";
	}

	protected function _cropPhoto($width, $height) {
		$path = $this->photoBehavior->filePath;
		if (!$path) {
			$path = Yii::getPathOfAlias('webroot');
			$path .= '/files/employees/photos/default.png';
		}
		$size = getimagesize($path);
		$photo = imagecreatefrompng($path);
		$w = $width;
		$h = ($w * $size[1]) / $size[0];
		if ($h < $height) {
			$h = $height;
			$w = ($h * $size[0]) / $size[1];
			$x = ($w - $width) / 2;
		}
		$dst = imagecreatetruecolor($width, $height);
		imagecopyresampled(
			$dst, $photo, 0, 0, $x, 0, $w, $h, $size[0], $size[1]
		);
		return $dst;
	}

	protected function _imageStringCutted($img, $font, $y, $x1, $x2, $text, $color,
		$align = "center") {
		$fontwidth = imagefontwidth($font);
		$fullwidth = strlen($text) * $fontwidth;
		$maxwidth = $x2 - $x1;
		$targetwidth = $fullwidth - (4 * $fontwidth);
		if ($fullwidth > $maxwidth) {
			for ($i = 0; $i < strlen($text) AND ((strlen($text) - ($i - 4)) * $fontwidth) > $targetwidth; $i++) {
				
			}
			$text = substr($text, 0, (strlen($text) - $i) - 4) . "...";
		}
		if ($align == "left") imagestring($img, $font, $x1, $y, $text, $color);
		elseif ($align == "right")
				imagestring($img, $font, $x2 - ((strlen($text) * $fontwidth)), $y, $text,
				$color);
		else
				imagestring($img, $font, ($x2 - $x1) / 2 - strlen($text) * $fontwidth / 2,
				$y, $text, $color);
	}

}